package com.hangim.pce.common.search.service.impl;

import com.hangim.pce.AmqpConstants;
import com.hangim.pce.common.search.domain.*;
import com.hangim.pce.common.search.enums.ESActionType;
import com.hangim.pce.common.search.enums.ESEntityType;
import com.hangim.pce.common.search.service.ESSyncAmqpService;
import com.hangim.pce.common.search.service.ESSyncService;
import com.hangim.pce.common.service.impl.BaseAmqpServiceImpl;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @see ESSyncAmqpService
 */
@Service
@RabbitListener(queues = AmqpConstants.ELASTICSEARCH_SYNC_QUEUE)
public class ESSyncAmqpServiceImpl extends BaseAmqpServiceImpl<ESPayLoad> implements ESSyncAmqpService {
    @Autowired
    private ESSyncService esSyncService;

    @Override
    public void send(ESPayLoad payLoad) {
        if (isAmqpEnable()) {
            this.amqpTemplate.convertAndSend(AmqpConstants.ELASTICSEARCH_SYNC_QUEUE, payLoad);
        } else {
            execute(payLoad);
        }
    }

    @Override
    public void execute(ESPayLoad payLoad) {
        if (ESActionType.SYNC.equals(payLoad.getAction())) {
            // 同步（更新）数据

            if (ESEntityType.DISEASE.equals(payLoad.getType())) {
                esSyncService.syncDisease((ESDisease) payLoad.getEntity());

            } else if (ESEntityType.DRUG.equals(payLoad.getType())) {
                esSyncService.syncDrug((ESDrug) payLoad.getEntity());

            } else if (ESEntityType.ELEMENT.equals(payLoad.getType())) {
                esSyncService.syncElement((ESElement) payLoad.getEntity());

            } else if (ESEntityType.SYMPTOM.equals(payLoad.getType())) {
                esSyncService.syncSymptom((ESSymptom) payLoad.getEntity());

            }

        } else if (ESActionType.REMOVE.equals(payLoad.getAction())) {
            // 同步（删除）数据
            Long entityId = payLoad.getEntity().getId();

            if (ESEntityType.DISEASE.equals(payLoad.getType())) {
                esSyncService.deleteDisease(entityId);

            } else if (ESEntityType.DRUG.equals(payLoad.getType())) {
                esSyncService.deleteDrug(entityId);

            } else if (ESEntityType.ELEMENT.equals(payLoad.getType())) {
                esSyncService.deleteElement(entityId);

            } else if (ESEntityType.SYMPTOM.equals(payLoad.getType())) {
                esSyncService.deleteSymptom(entityId);

            }

        }
    }
}
